package com.zhu.tool_test.spring_cache.aspect;

import com.linktopa.framework.common.model.response.ObjectResponseResult;
import com.linktopa.framework.common.model.response.ResponseResult;
import com.zhu.tool_test.spring_cache.anno.GgCacheable;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @program: tool_test
 * @description: 注解@GgCacheable的切面类
 * @author: ggBall
 * @create: 2021-01-03 17:15
 **/
@Component
@Aspect
@Slf4j
public class GgCacheAspect {

    @Autowired
    RedisTemplate redisTemplate;

    @Pointcut("@annotation(com.zhu.tool_test.spring_cache.anno.GgCacheable)")
    private void pointCut(){}

    @Around("pointCut() && @annotation(ggCacheable)")
    private void around(ProceedingJoinPoint joinPoint, GgCacheable ggCacheable) throws Throwable {
        //父类.class.isAssignableFrom(子类.class)
        //
        //子类实例 instanceof 父类类型
        // 获取 指定类型
        Class<? extends Object> aClass = ggCacheable.value();
        // 获取 指定key
        String key = ggCacheable.key();
        if (!ResponseResult.class.isAssignableFrom(aClass)) {
            if (List.class.isAssignableFrom(aClass)) {
                List ent = (List) joinPoint.proceed();
                redisTemplate.opsForHash().put(key, key,ent);
            }

            return;
        }

        ObjectResponseResult result = null;

        try {
             result = (ObjectResponseResult)joinPoint.proceed();
        } catch (Throwable throwable) {
            throwable.printStackTrace();
            log.error("数据转换错误");
        }

        Object data = result.getData();
        redisTemplate.opsForHash().put(key,key,data);
        log.info("ent保存完毕");
    }




}
